package com.growthserver.service.impl;

import com.github.pagehelper.PageHelper;
import com.growthserver.entity.TTaskComboEntity;
import com.growthserver.entity.TTaskInfoEntity;
import com.growthserver.entity.TTaskRuleDetailEntity;
import com.growthserver.entity.TTaskRuleEntity;
import com.growthserver.mapper.AppletMapper;
import com.growthserver.mapper.IntegralGrowthMapper;
import com.growthserver.mapper.TaskCenterMapper;
import com.growthserver.param.TTaskComboParam;
import com.growthserver.param.TaskInfoParam;
import com.growthserver.param.TaskInfoUserParam;
import com.growthserver.param.TaskNumUserParam;
import com.growthserver.service.TaskCenterService;
import com.growthserver.vo.TTaskComboVo;
import com.growthserver.vo.TaskInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaskCenterServiceImpl implements TaskCenterService {

    private final Logger LOGGER = LoggerFactory.getLogger(TaskCenterService.class);

    @Autowired
    private TaskCenterMapper taskCenterMapper;

    @Autowired
    private IntegralGrowthMapper integralGrowthMapper;

    @Autowired
    private AppletMapper appletMapper;

    /**
     * 任务规则创建
     * @param taskInfoVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTaskCenter(TaskInfoVo taskInfoVo) {
        //创建任务流程表和规则模板关联数据
        String taskId = String.valueOf(new Date().getTime());
        //校验规则模板是否可用
        //1 根据任务流程创建数据
        taskInfoVo.setTaskId(taskId);
        taskCenterMapper.createTaskCenter(taskInfoVo);
        //2 根据规则模板创建多条
        List<TTaskRuleEntity> ruleEntityList = taskInfoVo.getRuleEntityList();
        ruleEntityList.forEach(p->{p.setTaskId(taskId);
            p.setCreator(taskInfoVo.getCreator());
            p.setCreatedName(taskInfoVo.getCreatedName());});
        ruleEntityList.forEach(tTaskRuleEntity -> {
            taskCenterMapper.insertRuleTask(tTaskRuleEntity);
        });
        LOGGER.info("測試");
        //进行批量创建规则
//        taskCenterMapper.batchInsert(ruleEntityList);
    }

    /**
     * 规则校验
     * @param
     * @return
     */
    public boolean checkRule(TaskInfoVo taskInfoVo) {
        //TODO 校验,预审单号是否合格
        String auditStatus = taskCenterMapper.selectByBudgetNum(taskInfoVo.getBudgetRequestNum());
        if ("1".equals(auditStatus)) {
            //查询规则配置是否存在,是否启用,是否过期
            List<String> taskRuleIds = taskCenterMapper.selectByUserTypeAndType(taskInfoVo);
            //判断此类规则是否存在
            if (!taskRuleIds.isEmpty()) {
                //Todo 规则模板类型校验
                // 第一步 获取 规则模板数据
                List<TTaskRuleEntity> ruleEntityList = taskInfoVo.getRuleEntityList();
                for (TTaskRuleEntity tTaskRuleEntity : ruleEntityList
                ) {
                    //通过规则模板数据  用户类型,用户等级,任务类型 查询规则表是否存在此数据
                    List<TTaskRuleDetailEntity> tTaskRuleDetailEntities = integralGrowthMapper.selectByMouldAndUserType(tTaskRuleEntity.getUserType(),
                            tTaskRuleEntity.getMemberNum(), taskInfoVo.getTaskType());
                    if (!tTaskRuleDetailEntities.isEmpty()) {
                        //非空判断 规则表是否存在数据
                        for (TTaskRuleDetailEntity tTaskRuleDetailEntity : tTaskRuleDetailEntities
                        ) {
                            //如果此字段为空,那么默认为0 不连续
                            if(tTaskRuleEntity.getIsContinuous() == null){
                                tTaskRuleEntity.setIsContinuous("0");
                            }
                            // 判断 规则表中数据 是否已经存在 任务频率:天，周，月  此类数据 或者 签到类 是否连续类数据
                            if(taskInfoVo.getTaskType().equals("1")){
                                if(tTaskRuleEntity.getIsContinuous().equals(tTaskRuleDetailEntity.getIsContinuous())){
                                    return false;
                                }else {
                                    return true;
                                }
                            }
                            if (tTaskRuleEntity.getTaskFrequency().equals(tTaskRuleDetailEntity.getTaskFrequency())){
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }else {
                        return true;
                    }
                }
            }else {
                return true;
            }
        }
        return false;
    }

    /**
     * 任务展示
     * @param taskInfoParam
     * @return
     */
    @Override
    public List<TTaskInfoEntity> taskDisplay(TaskInfoParam taskInfoParam) {
        PageHelper.startPage(taskInfoParam.getPageNo(), taskInfoParam.getPageSize());
        return taskCenterMapper.taskDisplay(taskInfoParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTask(TTaskInfoEntity tTaskInfoEntity) {
        taskCenterMapper.updateTask(tTaskInfoEntity);
        List<TTaskRuleEntity> ruleEntityList = tTaskInfoEntity.getRuleEntityList();
        ruleEntityList.forEach(p->{p.setModifier(tTaskInfoEntity.getModifier());p.setModifyName(tTaskInfoEntity.getModifyName());});

        //查询 taskId 下对应的所有规则
        List<String> list = taskCenterMapper.selectRuleDetailByTaskId(tTaskInfoEntity.getTaskId());
        List<String> taskRuleIdList = ruleEntityList.stream()
                .map(TTaskRuleEntity::getTaskRuleId)
                .collect(Collectors.toList());
        list.removeIf(taskRuleIdList::contains);
        //如果不为空,进行删除
        if(!list.isEmpty()){
            taskCenterMapper.deleteTaskRule(list);
        }

        for (TTaskRuleEntity tTaskRuleEntity:ruleEntityList
             ) {
            if("".equals(tTaskRuleEntity.getTaskRuleId()) || tTaskRuleEntity.getTaskRuleId() == null){
                tTaskRuleEntity.setTaskId(tTaskInfoEntity.getTaskId());
                tTaskRuleEntity.setCreator(tTaskInfoEntity.getModifier());
                tTaskRuleEntity.setCreatedName(tTaskInfoEntity.getModifyName());
                taskCenterMapper.insertRuleTask(tTaskRuleEntity);
            }else {
                taskCenterMapper.updateTaskRule(tTaskRuleEntity);
            }
        }

    }

    @Override
    public void upDownTask(String isEnable,String taskId) {
        taskCenterMapper.upDownTask(isEnable,taskId);
    }

    /**
     * 单个任务规则详情查看
     * @param taskId
     * @return
     */
    @Override
    public List<TTaskRuleEntity> selectTaskRules(String taskId) {
        return taskCenterMapper.selectByTaskId(taskId);
    }

    @Override
    public void deleteTask(String taskId) {
        taskCenterMapper.deleteTask(taskId);
    }

    @Override
    public void createTaskNum(TTaskComboVo tTaskComboVo) {
        //规则校验 同一时间内只能存在一条进行中的社区任务
        String exist = taskCenterMapper.selectTaskComboIsExist();
        if(exist == null) {
            String taskId = String.valueOf(new Date().getTime());
            tTaskComboVo.setTaskId(taskId);
            taskCenterMapper.createTaskNum(tTaskComboVo);
        }else {

        }
    }

    @Override
    public void updateTaskNum(TTaskComboEntity tTaskComboEntity) {
        taskCenterMapper.updateTaskNum(tTaskComboEntity);
    }

    @Override
    public void upDownTaskNum(String isEnable,String taskId) {
        //判断是否存在一条已发布切在进行中的任务
        String exist = taskCenterMapper.selectTaskComboIsExist();
        if(exist != null && isEnable.equals("1")){
            LOGGER.info("存在一条已发布切在进行中的任务,不予许修改状态为发布");
        }else {
            taskCenterMapper.upDownTaskNum(isEnable,taskId);
        }
    }

    @Override
    public List<TTaskComboEntity> taskNumDisplay(TTaskComboParam tTaskComboParam) {
        PageHelper.startPage(tTaskComboParam.getPageNo(),tTaskComboParam.getPageSize());
       return taskCenterMapper.taskNumDisplay(tTaskComboParam);
    }

    @Override
    public void deleteTaskNum(String taskId) {
        taskCenterMapper.deleteTaskNum(taskId);
    }

    @Override
    public List<HashMap<String,String>> getUserMemberInfo(TTaskComboParam tTaskComboParam) {
        List<String> userMemberInfo = taskCenterMapper.getUserMemberInfo();
        List<HashMap<String,String>> arrayList = new ArrayList<>();
        for (String values:userMemberInfo
             ) {
            HashMap<String, String> map = new HashMap<>();
            String[] split = values.split(",");
            map.put("levelNum",split[0]);
            map.put("levelName",split[1]);
            map.put("userType",split[2]);
            arrayList.add(map);
        }
        return arrayList;
    }

    /**
     * 用户任务列表
     * @param userId
     * @return
     */
    @Override
    public List<TaskInfoUserParam> taskDisplayByUser(String userId) {
        List<TaskInfoUserParam> taskInfoUserParams = taskCenterMapper.taskDisplayByUser(userId);
        taskInfoUserParams.forEach(p->{
            if (p.getTaskType().equals("10")) {p.setStatus("1");   }});
        return taskInfoUserParams;
    }

    /**
     * 用户完成任务统计
     * @param userId
     * @return
     */
    @Override
    public TaskNumUserParam taskDisplayByUserNum(String userId) {
        List<TaskInfoUserParam> taskInfoUserParams = taskDisplayByUser(userId);
        if (taskInfoUserParams.size() > 0) {
            TaskNumUserParam taskNumUserParam = new TaskNumUserParam();
            TaskInfoUserParam taskInfoUserParam = taskInfoUserParams.get(0);
            String taskNums = taskInfoUserParam.getTaskNums();
            int growthValue = taskInfoUserParams.stream().mapToInt(p -> Integer.parseInt(p.getGrowthValue())).sum();
            int integralValue = taskInfoUserParams.stream().mapToInt(p -> Integer.parseInt(p.getIntegralValue())).sum();
            taskNumUserParam.setGrowthValue(growthValue);
            taskNumUserParam.setIntegralValue(integralValue);
            //获取已完成数
            List<TaskInfoUserParam> filteredTaskInfoUserParams = taskInfoUserParams.stream()
                    .filter(p -> p.getStatus().equals("1"))
                    .collect(Collectors.toList());
            if (Integer.parseInt(taskNums) > filteredTaskInfoUserParams.size()) {
                int residueTaskNum = Integer.parseInt(taskNums) - filteredTaskInfoUserParams.size();
                taskNumUserParam.setResidueTaskNum(String.valueOf(residueTaskNum));
                if (filteredTaskInfoUserParams.size() == 0) {
                    taskNumUserParam.setCompleteTaskNum("0");
                } else {
                    taskNumUserParam.setCompleteTaskNum(String.valueOf(filteredTaskInfoUserParams.size()));
                }
            } else {
                taskNumUserParam.setResidueTaskNum(String.valueOf(0));
                taskNumUserParam.setResidueTaskNum("0");

                taskNumUserParam.setCompleteTaskNum(String.valueOf(filteredTaskInfoUserParams.size()));
            }
            return taskNumUserParam;
        }
        return null;
    }

}
